package dal

import (
	"database/sql"
	"fmt"

	log "github.com/omidnikta/logrus"
)

const (
	TBL_TASKS = "tasks"
)

type taskModel struct{}

var _taskModel = &taskModel{}

func TaskModel() *taskModel {
	return _taskModel
}

func (t *taskModel) Get(jobId string) ([]*Task, error) {
	tasks := []*Task{}
	sqlStr := fmt.Sprintf("SELECT id,job_id,retry,addr,path,body,start_at FROM %s WHERE job_id='%s'", TBL_TASKS, jobId)
	rows, err := db.Query(sqlStr)
	if nil != err {
		if sql.ErrNoRows == err {
			log.Warnf(sqlStr, sql.ErrNoRows)
			return tasks, nil
		}

		log.Errorln(err)
		return nil, err
	}

	for rows.Next() {
		var task Task
		err = rows.Scan(&task.ID, &task.JobId, &task.Retry, &task.Addr, &task.Path, &task.Body, &task.StartAt)
		if nil != err {
			log.Errorln(err)
			return nil, err
		}
		tasks = append(tasks, &task)
	}

	return tasks, nil
}

func (t *taskModel) GetById(id string) (*Task, error) {
	sqlStr := fmt.Sprintf("SELECT id,job_id,retry,addr,path,body,start_at FROM %s WHERE id='%s'", TBL_TASKS, id)
	row := db.QueryRow(sqlStr)

	var task Task
	err := row.Scan(&task.ID, &task.JobId, &task.Retry, &task.Addr, &task.Path, &task.Body, &task.StartAt)
	if nil != err {
		log.Errorln(err)
		return nil, err
	}

	return &task, nil
}
